var websocket = null;
var olineUsers = 0;
var userno;
while (!userno){
    userno = prompt('请输入昵称')
}
document.querySelector('#type').value = userno
//判断当前浏览器是否支持WebSocket
if ('WebSocket' in window) {
    //ws://42.192.208.23:8080/webSocket/websocket/
    websocket = new WebSocket("ws://localhost:8081/chat_war_exploded/websocket/" + userno);
} else {
    alert('当前浏览器 Not support websocket')
}

//连接发生错误的回调方法
websocket.onerror = function () {
    alert("WebSocket连接发生错误");
};

//连接成功建立的回调方法
websocket.onopen = function () {
    alert('连接成功')
    showCurrentUserCount(1)
}

//接收到消息的回调方法
websocket.onmessage = function (event) {

    let str = event.data.split('-');
    if(str[0]==='**|online|**'&&str.length===2){
        showCurrentUserCount(str[1]);
    }else {
        appendMessage(str[0],str[1],'message')
    }

}

//连接关闭的回调方法
websocket.onclose = function () {
    setMessageInnerHTML("WebSocket连接关闭");
}

//监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
window.onbeforeunload = function () {
    closeWebSocket();
}

//将消息显示在网页上
function setMessageInnerHTML(sendMessage) {
    document.getElementById('message').innerHTML += sendMessage + '<br/>';
}

//关闭WebSocket连接
function closeWebSocket() {
    websocket.close();
}

enterKey()
//发送消息
function send() {

    var message = document.querySelector('#text').value;; //要发送的消息内容
    // document.getElementById('message').innerHTML += (now + "发送人：" + userno + '<br/>' + "---" + message) + '<br/>';
    // document.getElementById('message').style.color = "red";
    var ToSendUserno = "4567"; //接收人编号：4567
    message = message //将要发送的信息和内容拼起来，以便于服务端知道消息要发给谁
    websocket.send(message);
    appendMessage(userno,message,'my-message')
}
//获取当前时间
function getNowFormatDate() {
    var date = new Date();
    var seperator1 = "-";
    var seperator2 = ":";
    var month = date.getMonth() + 1;
    var strDate = date.getDate();
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
    }
    var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate +
        " " + date.getHours() + seperator2 + date.getMinutes() +
        seperator2 + date.getSeconds();
    return currentdate;
}


function appendMessage(userName='匿名',message,style){
    let div = document.createElement('div');
    // let message = document.querySelector('#text').value;
    let date = new Date;
    let now = `${date.getFullYear()}-${date.getMonth()+1}-${date.getDate()} ${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`;
    let messageBox = document.querySelector(".message-window");
    div.className = style
    div.innerHTML = `<strong>${userName}:</strong> ${message}<br> <p style="font-size:1px">${now}</p>`
    messageBox.append(div)
    messageBox.scrollTop = messageBox.scrollHeight; 
}


function enterKey(){
    let text = document.querySelector('#text');
    text.onkeypress=function (e){
        if(e.keyCode===13){
            send(text.value);
             text.value= '';
        }
    }
}

function showCurrentUserCount(count){
    let hint = document.querySelector('.header .alert strong');
    olineUsers = count;
    hint.innerHTML=`当前在线人数(${count})`;
}

